<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace common\helpers;

use Yii;

class EBC3Des {
    /*     * 加密
     * @param $text string 文本内容
     * @param $key string 秘钥 max 24
     * @return string
     */

    public function encrypt($text, $key) {
        $size = @mcrypt_get_iv_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_ECB);
        $iv = @mcrypt_create_iv($size, MCRYPT_RAND);

        $pad = $size - (strlen($text) % $size);
        $text = $text . str_repeat(chr($pad), $pad);

        $td = @mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
        @mcrypt_generic_init($td, $key, $iv);
        $data = base64_encode(@mcrypt_generic($td, $text));
        @mcrypt_generic_deinit($td);
        @mcrypt_module_close($td);
        return $data;
    }

    /**
     * 解密
     * @param $text
     * @param $key
     */
    public function decrypt($text, $key) {
        $iv = @mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $td = @mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');
        @mcrypt_generic_init($td, $key, $iv);
        $data = $this->pkcs5UnPad(@mdecrypt_generic($td, base64_decode($text)));
        @mcrypt_generic_deinit($td);
        @mcrypt_module_close($td);
        return $data;
    }

    /**
     * @param $text
     * @return string
     */
    private function pkcs5Pad($text) {
        $pad = 8 - (strlen($text) % 8);
        return $text . str_repeat(chr($pad), $pad);
    }

    /**
     * @param $text
     * @return bool|string
     */
    private function pkcs5UnPad($text) {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text)) {
            return false;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }
        return substr($text, 0, -1 * $pad);
    }

}
